package com.xmb.wechat.view.wechat.chat;

import android.app.Activity;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.os.Handler;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.widget.ImageView;

import com.bigkoo.pickerview.builder.TimePickerBuilder;
import com.bigkoo.pickerview.listener.OnTimeSelectListener;
import com.bigkoo.pickerview.view.TimePickerView;
import com.blankj.utilcode.util.BarUtils;
import com.xmb.wechat.R;
import com.xmb.wechat.R2;
import com.xmb.wechat.adapter.ChatMsgAdapter;
import com.xmb.wechat.application.WechatStartApplication;
import com.xmb.wechat.base.BaseActivity;
import com.xmb.wechat.bean.WechatContactBean;
import com.xmb.wechat.bean.WechatMsgBean;
import com.xmb.wechat.bean.WechatMsgBean_;
import com.xmb.wechat.definterface.WhoSendListener;
import com.xmb.wechat.dialog.WhoSendDialog;
import com.xmb.wechat.entity.WechatAppInfoBean;
import com.xmb.wechat.lsn.OnRefreshListener;
import com.xmb.wechat.lsn.SendMsgCenter;
import com.xmb.wechat.util.PicLoadUtils;
import com.xmb.wechat.widget.ChartBar;
import com.xmb.wechat.widget.ChartBarExtend;
import com.xmb.wechat.widget.TitleLayout;

import java.util.Date;
import java.util.List;

import butterknife.BindView;
import io.objectbox.Box;

/**
 * 聊天界面
 */
public class WechatDanliaoDetailActivity extends BaseActivity implements OnRefreshListener {

    @BindView(R2.id.title_layout)
    TitleLayout    mTitleLayout;
    @BindView(R2.id.iv_chat_bg)
    ImageView      mIvChatBg;
    @BindView(R2.id.msgContent)
    RecyclerView   mRecyclerView;
    @BindView(R2.id.chat_bar)
    ChartBar       mChartBar;
    @BindView(R2.id.layout_add_open)
    ChartBarExtend mChartBarExtend;

    private WechatContactBean  contactBean;
    private Box<WechatMsgBean> msgBox;
    private ChatMsgAdapter     msgAdapter;
    private WhoSendDialog      mWhoSendDialog;
    private int                mStatusBarHeight;

    public WechatDanliaoDetailActivity() {
        super(R.layout.wechat_activity_danliao_detail);
    }

    public static void start(Activity act, WechatContactBean wechatContactBean) {
        Intent it = new Intent(act, WechatDanliaoDetailActivity.class);
        it.putExtra("data", wechatContactBean);
        act.startActivity(it);
    }

    @Override
    protected void initView() {
        setStatusBarColor(Color.parseColor("#ededed"));
        setNavigationColor(Color.parseColor("#f7f7f7"));

        mChartBar.adjustViewSize();
        mTitleLayout.adjustViewSize();
        //数据
        contactBean = (WechatContactBean) getIntent().getSerializableExtra("data");
        if (contactBean == null)
            return;
        mTitleLayout.setMuteAndStrongRemind(contactBean.isMute(),contactBean.isStrongRemind());
        //adapter
        mRecyclerView.setLayoutManager(new LinearLayoutManager(this));
        msgAdapter = new ChatMsgAdapter(this, false, contactBean, null, this);
        mRecyclerView.setAdapter(msgAdapter);
        Log.e("sana", contactBean.toString());
        //设置聊天背景
        String bg = WechatAppInfoBean.getWechat(this).getChatCommonBG();
        if (TextUtils.isEmpty(contactBean.getChatBG())) {//没有设置个人的背景图
            if (TextUtils.isEmpty(bg)) {
                msgAdapter.setIsHasBgPic(false);
                PicLoadUtils.loadChatBg("", mIvChatBg);
            } else {
                PicLoadUtils.loadChatBg(bg, mIvChatBg);
                msgAdapter.setIsHasBgPic(true);
            }
        } else {//个人背景不为空
            if (TextUtils.equals(contactBean.getChatBG(), "default")) {
                msgAdapter.setIsHasBgPic(false);
                PicLoadUtils.loadChatBg("", mIvChatBg);
            } else {
                PicLoadUtils.loadChatBg(contactBean.getChatBG(), mIvChatBg);
                msgAdapter.setIsHasBgPic(true);
            }
        }
        //聊天模块
        mChartBar.init(this, new ChartBar.OnChatBarClickCallBack() {
            @Override
            public void onVoiceClick() {
                mChartBar.hideExpand();
                WechatChatAddVoiceActivity.start(WechatDanliaoDetailActivity.this, contactBean);
            }

            @Override
            public void onAddClick() {
                mChartBar.hideExpand();
                new Handler().postDelayed(() -> mChartBarExtend.setVisibility(View.VISIBLE), 50);
            }

            @Override
            public void onSendClick() {
                if (mWhoSendDialog == null) {
                    mWhoSendDialog = new WhoSendDialog(WechatDanliaoDetailActivity.this, new WhoSendListener() {
                        @Override
                        public void onMe() {
                            onClickSend(WechatContactBean.instanceNewContactMe(WechatDanliaoDetailActivity.this));
                        }

                        @Override
                        public void onOther() {
                            onClickSend(contactBean);
                        }
                    });
                }
                mWhoSendDialog.show();
            }

            @Override
            public void onSendLongClick(String msg) {
                onClickSend(contactBean);
            }
        });
        //聊天模块拓展
        mChartBarExtend.init(new ChartBarExtend.onChatBarExtendClickCallBack() {
            @Override
            public void onVoiceClick() {
                mChartBarExtend.setVisibility(View.GONE);
                WechatChatAddVoiceActivity.start(WechatDanliaoDetailActivity.this, contactBean);
            }

            @Override
            public void onPictureClick() {
                mChartBarExtend.setVisibility(View.GONE);
                WechatChatAddImgActivity.start(WechatDanliaoDetailActivity.this, contactBean);
            }

            @Override
            public void onRedPacketClick() {
                mChartBarExtend.setVisibility(View.GONE);
                WechatChatAddRedpkgActivity.start(WechatDanliaoDetailActivity.this, contactBean);
            }

            @Override
            public void onZhuanZhangClick() {
                mChartBarExtend.setVisibility(View.GONE);
                WechatChatAddZhuanZhangActivity.start(WechatDanliaoDetailActivity.this, contactBean);
            }

            @Override
            public void onVideoCallClick() {
                mChartBarExtend.setVisibility(View.GONE);
                showChoiceWhenVideoCall();
            }

            @Override
            public void onTimeClick() {
                mChartBarExtend.setVisibility(View.GONE);
                onClickTime();
            }

            @Override
            public void onSystemTipClick() {
                mChartBarExtend.setVisibility(View.GONE);
                WechatChatAddSystipActivity.start(WechatDanliaoDetailActivity.this, contactBean);
            }

            @Override
            public void onBussinessClick() {
                mChartBarExtend.setVisibility(View.GONE);
                WechatChatAddBCardsActivity.start(WechatDanliaoDetailActivity.this, contactBean);
            }

            @Override
            public void onRedPacketReceive() {
                //单聊没有收红包
            }
        }, false);
        mStatusBarHeight = BarUtils.getStatusBarHeight();
    }

    //刷新数据
    @Override
    protected void onResume() {
        super.onResume();
        refresh();
    }

    //点击空白隐藏展开项
    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        if (ev.getAction() == MotionEvent.ACTION_DOWN) {
            float clickHeight = ev.getY() - mStatusBarHeight;
            if (clickHeight < mChartBarExtend.getY() && mChartBarExtend.getVisibility() == View.VISIBLE)
                mChartBarExtend.setVisibility(View.GONE);
            if (clickHeight < mChartBar.getY())
                mChartBar.hideExpand();
        }
        return super.dispatchTouchEvent(ev);
    }

    @Override
    public void refresh() {
        mTitleLayout.setTitleLeft(contactBean.getName());
        if (msgBox == null)
            msgBox = WechatStartApplication.getBoxStore(this).boxFor(WechatMsgBean.class);
        //聊天记录：
        List<WechatMsgBean> msgs = msgBox.query().equal(WechatMsgBean_.talkerID, contactBean.getId()).equal(WechatMsgBean_.isRoomChat, false).build().find();
        msgAdapter.getData().clear();
        msgAdapter.getData().addAll(msgs);
        msgAdapter.notifyDataSetChanged();
        mRecyclerView.scrollToPosition(msgAdapter.getItemCount() - 1);
    }

    //点击发送按钮
    private void onClickSend(WechatContactBean sender) {
        String content = mChartBar.getSendValue();
        if (TextUtils.isEmpty(content))
            return;
        SendMsgCenter.sendString(new SendMsgCenter.SendMsgListener() {
            @Override
            public void onSendSuc() {
                refresh();
                mChartBar.clearInput();
            }

            @Override
            public void onSendError(String errorMsg) {

            }
        }, sender.getId(), false, contactBean.getId(), content);
    }

    //视频语音通话选择框
    private void showChoiceWhenVideoCall() {
        new AlertDialog.Builder(this).setItems(new String[]{"视频通话", "语音通话"},
                new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        switch (which) {
                            case 0:
                                WechatChatAddCallActivity.start(WechatDanliaoDetailActivity.this, contactBean
                                        , true);
                                break;
                            case 1:
                                WechatChatAddCallActivity.start(WechatDanliaoDetailActivity.this, contactBean
                                        , false);
                                break;
                        }
                    }
                }).setNegativeButton("取消", null).show();
    }

    //选择时间
    private void onClickTime() {
        TimePickerView pvTime = new TimePickerBuilder(this, new OnTimeSelectListener() {
            @Override
            public void onTimeSelect(Date date, View v) {//选中事件回调
                SendMsgCenter.sendTime(new SendMsgCenter.SendMsgListener() {
                    @Override
                    public void onSendSuc() {
                        refresh();
                    }

                    @Override
                    public void onSendError(String errorMsg) {

                    }
                }, false, contactBean.getId(), date);

            }
        })
                .setType(new boolean[]{true, true, true, true, true, false})// 默认全部显示
                .setCancelText("取消")//取消按钮文字
                .setSubmitText("确定")//确认按钮文字
                .setTitleSize(20)//标题文字大小
                .setTitleText("时间")//标题文字
                .setOutSideCancelable(true)//点击屏幕，点在控件外部范围时，是否取消显示
                .isCyclic(true)//是否循环滚动
                .setSubmitColor(getResources().getColor(R.color.wechat_tab_bg_green))//确定按钮文字颜色
                .setCancelColor(getResources().getColor(R.color.wechat_tab_bg_green))//取消按钮文字颜色
                .setLabel("年", "月", "日", "时", "分", "秒")//默认设置为年月日时分秒
                .isCenterLabel(true) //是否只显示中间选中项的label文字，false则每项item全部都带有label。
                .build();
        pvTime.show();
    }

    @Override
    protected void onPause() {
        super.onPause();
        if (mChartBar != null)
            mChartBar.hideExpand();
    }

    @Override
    public void onBackPressed() {
        if (mChartBarExtend.getVisibility() == View.VISIBLE) {
            mChartBarExtend.setVisibility(View.GONE);
        } else if (mChartBar.isEmojiVisible()) {
            mChartBar.hideExpand();
        } else {
            finish();
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mWhoSendDialog != null) {
            mWhoSendDialog.dismiss();
            mWhoSendDialog = null;
        }
    }
}
